package leetcode.每日一题;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author ：zsy
 * @date ：Created 2022/11/13 5:59 PM
 * @description：
 */
public class 自定义字符串排序 {
    @Test
    public void test() {

    }

    /*class Solution {
        public String customSortString(String order, String s) {
            int[] factor = new int[26];
            // 存储s
            for (int i = 0; i < s.length(); i++) {
                factor[s.charAt(i) - 'a']++;
            }
            StringBuilder builder = new StringBuilder();
            // 按照order顺序排列s
            for (int i = 0; i < order.length(); i++) {
                char ch = order.charAt(i);
                for (int j = 0; j < factor[ch - 'a']; j++) {
                    builder.append(ch);
                }
                factor[ch - 'a'] = 0;
            }
            // 处理剩余字符
            for (int i = 0; i < 26; i++) {
                for (int j = 0; j < factor[i]; j++) {
                    builder.append((char)(i + 'a'));
                }
            }
            return builder.toString();
        }
    }*/

    class Solution {
        public String customSortString(String order, String s) {
            int[] val = new int[26];
            for (int i = 0; i < order.length(); i++) {
                val[order.charAt(i) - 'a'] = i + 1;
            }
            Character[] arr = new Character[s.length()];
            for (int i = 0; i < s.length(); i++) {
                arr[i] = s.charAt(i);
            }
            Arrays.sort(arr, Comparator.comparingInt(a -> val[a - 'a']));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                builder.append(arr[i]);
            }
            return builder.toString();
        }
    }
}
